package Filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Model.Employee;

/**
 * @author TONY
 *
 */
public class LoginFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest resq, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpServletRequest request = (HttpServletRequest) resq;
		String currentURL = request.getRequestURI();
		HttpSession session = request.getSession();
		Employee employee=(Employee)session.getAttribute("employee");		
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());
	
		 if ("/Login.jsp".equals(targetURL)||"/Login.do".equals(targetURL)||session.getAttribute("employee") != null) 
		 {
			 chain.doFilter(request, response);	 			  
		 }	
		 else
		 {			
			    //System.out.println("request.getContextPath()=" + request.getContextPath());
			    response.sendRedirect(request.getContextPath() + "/Login.jsp");			    		
		 }
      
			 
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
